package org.duang.handles;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.duang.common.dto.HeadDto;
import org.duang.common.dto.ReturnDto;
import org.duang.common.enums.IEnums;
import org.duang.common.exceptios.ServiceException;
import org.duang.config.Config;
import org.duang.config.InstanceFactory;
import org.duang.core.Action;
import org.duang.core.ActionInvocation;
import org.duang.core.Controller;
import org.duang.core.IocHepler;
import org.duang.kit.ObjectKit;
import org.duang.kit.ToolsKit;
import org.duang.render.JsonRender;
import org.duang.render.Render;

import com.esotericsoftware.reflectasm.MethodAccess;

public class ActionHandle implements IHandle {

	private static Render jsonRender = JsonRender.init();

	public final void execute(String target, HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 请求的URL中如果包含有.  则全部当作是静态文件的请求处理，直接返回
		if (target.indexOf(".") != -1)  return;
		
		if(target.indexOf(";") != -1){
			target = target.substring(0,target.indexOf(";"));
		}
		
		// 暂不支持根目录请求
		if("/".equals(target)) {
			return;
		}

//		String[] urlParams = { null };

		Action action = InstanceFactory.getActionMapping().get(target);
		
		if(action == null){
			returnErrorJson(1, "action is null or access denied", request, response);
			return;
		}
	
		Class<? extends Controller> controllerClass = action.getControllerClass();

		Controller controller = ObjectKit.newInstance(controllerClass); // 多例

		IocHepler.injectService2Controller(controller, controllerClass); // 依赖注入Service到controller

		controller.init(request, response); // 传入request, response到Controller

		MethodAccess actionMethod = InstanceFactory.getMethodAccessMaps().get(action.getActionKey());
		
		if(actionMethod == null){
			actionMethod = MethodAccess.get(action.getControllerClass());		//引入reflectasm(第三反射库)执行
			InstanceFactory.getMethodAccessMaps().put(action.getActionKey(), actionMethod);
		}
		
		try {
			new ActionInvocation(action, controller, actionMethod).invoke();	// 反射执行该方法
		} catch (ServiceException se) {
			se.printStackTrace();
			int code =1;
			String message = "";
			IEnums enums = se.getEnums();
			if (ToolsKit.isEmpty(enums)) {
				code =  se.getCode();
				message = se.getMessage();
			} else {
				code = enums.getCode();
				message = enums.getMessage();
			}
			returnErrorJson(code, message, request, response);
			return;
		}catch (RuntimeException e) {
			e.printStackTrace();
			returnErrorJson(1, e.getMessage(), request, response);
			return;
		}

		Render render = controller.getRender(); // 取出渲染模板		

		if (null == render) {
			render = jsonRender; // 默认为为JSON模板
		}
		
		render.setContext(controller.getRequest(), controller.getReqsponse()).render(); // 调用方法
	}
	
	private final void returnErrorJson(int code, String errorMsg, HttpServletRequest request, HttpServletResponse response){
		ReturnDto<Map<String,String[]>> dto = new ReturnDto<Map<String,String[]>>();
		HeadDto head = new HeadDto();
		head.setRet(code);
		head.setMsg(errorMsg);
		head.setUri(request.getRequestURI());
		dto.setHead(head);
		String[] requestTime = {ToolsKit.getCurrentDate(Config.getDefaultDateFormat())};
		request.setAttribute("requestTime", requestTime);
		Map<String, String[]> paramMap = request.getParameterMap();
		dto.setData(paramMap);
		jsonRender.setObj(dto);
		jsonRender.setContext(request, response).render();
	}
}
